#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/1 22:03
# @Author : 闫峰
# @File    : set_amazon_sales_ban_es.py
import json
import os
import re
import threading
import time

import requests

from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.sql_server_utils import MSSQL
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
from functools import partial

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class Set_amazon_sales_ban:

    def set_amazon_sales_ban(self):

        res_list = []
        offset_start = 0

        while True:
            sql1 = """
            SELECT top 100 id FROM [dbo].[RB_Product] WHERE id > %s ORDER BY id 
            """
            res1 = self.db.ExecQuery(sql1, (offset_start,))

            if res1:
                res1 = list(map(lambda x: x[0], res1))
                offset_min = min(res1)
                offset_max = max(res1)
                res_list.append((offset_min, offset_max))
                offset_start = offset_max
            else:
                break
        return res_list

    def handler(self, id_interval):
        db = MSSQL(ensure_path_sep("\\config\\config.yaml"), "sqlserver_db_erp_base")
        insert_db = Database(ensure_path_sep("\\config\\ceshi_mysql_config.yaml"), "log_db")

        sql2 = """
        SELECT top 1000 sku FROM [dbo].[RB_Product] WHERE id >= %s AND id <= %s
        """
        res2 = db.ExecQuery(sql2, (id_interval[1], id_interval[2]))
        sku_list = list(map(lambda x: x[0], res2))
        for data in sku_list[:]:
            sku = "'" + data + "'"
            self.handler_sku(sku)
        # new_lst = ["'" + x + "'" for x in sku_list]
        # new_s = ",".join(new_lst)
        # for sku in sku_list:
        update_sql = """
        UPDATE znkdceshilog.excuce_queue SET STATUS=1 WHERE id=%s
        """
        row = insert_db.execute(update_sql, (id_interval[0],))
        if row == 0:
            ERROR.logger.error(f"id_interval={id_interval}更新失败")
            raise
        INFO.logger.info(f"thread_id={threading.current_thread().ident} 执行完了id_interval={id_interval}\n ")

    def re_str(self, row):
        pattern = r"产品标签为"
        match = re.search(pattern, row['operationtxt'])
        if match:
            # print("匹配成功！")
            return True
        else:
            # print("未找到匹配的文本。")
            return False

    def handler_sku(self, sku):
        headers = {
            "Authorization": "Basic aXJvYm90Ym94OmkxcjVvOEJvdGJveA=="
        }
        url = "http://erplog.zhcxkj.com/api/systems/logs/List"

        current = 1

        while True:
            json_data = {
                "input": {
                    "tableName": "RB_Product_Log_1",
                    "equal": [
                        {
                            "fieldName": "CustomerID",
                            "value": "1",
                            "dataType": 1
                        },
                        {
                            "fieldName": "SKU",
                            "value": sku,
                            "dataType": 1
                        }
                    ],
                    "ranges": [
                        {
                            "fieldName": "AddTime",
                            "dataType": 2,
                            "beginValueGX": "gt",
                            "beginValue": "2023-07-06",
                            "endValueGX": "lt",
                            "endValue": "2023-09-01"
                        }
                    ],
                    "orderBy": [
                        {
                            "fieldName": "AddTime",
                            "value": "-1",
                            "dataType": 0
                        }
                    ],
                    "current": current,
                    "pageSize": 500
                }
            }

            res33 = requests.post(url=url, json=json_data, headers=headers, timeout=100)
            if res33.status_code != 200:
                continue
            try:
                res3 = res33.json()
            except Exception as e:
                print(res33)
                raise e

            # try:
            #     res3 = requests.post(url=url, json=json_data, headers=headers, timeout=100)
            #     res3 = json.loads(res3.text)
            # except json.decoder.JSONDecodeError as e:
            #     print("JSON 解析错误：", )
            # except Exception as e:
            #     print("其他错误：", e)

            if not res3:
                ERROR.logger.error(f"res3没有结果")
                continue
            if not res3.get("data"):
                # INFO.logger.info(f"sku={sku}遍历完成")
                break
            if res3.get('data').get('dataSource'):
                current += 1
                res4 = res3.get('data').get('dataSource')
                res4 = list(filter(self.re_str, res4))
                if not res4:
                    continue
                data_list = list(
                    map(lambda data: (data.get('id'), data.get('sku'), data.get('operationtxt'), data.get('addtime')),
                        res4))
                # 插入数据库
                insert_sql = """
                            INSERT IGNORE INTO znkdceshilog.set_amazon_sales_ban_copy1_copy1_copy1_copy1 (erp_id, sku, text,addtime)
                            VALUES (%s, %s, %s,%s);
                            """
                row1 = insert_db.execute_many(insert_sql, data_list)
                if row1 == 0:
                    ERROR.logger.error(f"""
                            INSERT IGNORE INTO znkdceshilog.set_amazon_sales_ban_copy1_copy1_copy1_copy1 (erp_id, sku, text,addtime)
                            VALUES (%s, %s, %s,%s);
                            插入失败
                            data_list={data_list}
                                """)
            else:
                # INFO.logger.info(f"sku={sku}遍历完成")
                break
        # INFO.logger.info(f"sku={sku}遍历完成")

if __name__ == '__main__':
    # Set_amazon_sales_ban().set_amazon_sales_ban()
    #
    t = Set_amazon_sales_ban()
    insert_db = Database(ensure_path_sep("\\config\\ceshi_mysql_config.yaml"), "log_db")
    sql = """
    SELECT id,offset_min,offset_max FROM `excuce_queue` WHERE STATUS=0
    """
    res = insert_db.fetch_all_tuple(sql, ())
    # for data in res:
    #     t.handler(data)
    # print()
    # res_list = t.set_amazon_sales_ban()
    # print(res_list)
    # id_interval = (10845, 1209828, 1209927)
    # Set_amazon_sales_ban().handler(id_interval)
    # 创建线程池，最多同时执行5个任务
    executor = ThreadPoolExecutor(max_workers=8)
    tasks = []
    for i in range(len(res)):
        # 使用funools.partial函数创建一个新的函数，将参数绑定到函数中
        new_task = partial(t.handler, res[i])
        # executor.submit(new_task)
        tasks.append(executor.submit(new_task))

    # 处理已完成的任务
    # for future in as_completed(tasks):
    #     try:
    #         result = future.result()
    #         # 处理任务执行的结果
    #         print(result)
    #     except Exception as e:
    #         # 处理任务执行出的异常
    #         print(f"任务{i}执行出现异常，参数为{new_task.args}")
    #         raise

    #关闭线程池
    executor.shutdown()
